import React, { PureComponent, Fragment } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Table, Button, Input, message, Popconfirm, Divider, Modal, TreeSelect, Select } from 'antd';
import styles from './style.less';
import { findItemByKey, depCopy, getLastId, findNameById, deleteItemByKey } from '../../utils/utils';
import moment from 'moment';
const Option = Select.Option;
const { confirm } = Modal;

export default class TableForm extends PureComponent {
  index = 0;
  cacheOriginData = {};

  toggleEditable = (e, key) => {
    e.preventDefault();

    const { menuList, dispatch } = this.props;
    const newData = depCopy(menuList);
    const target = findItemByKey(key, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        this.cacheOriginData[key] = { ...target };
      }
      target.editable = !target.editable;
      dispatch({
        type: 'menuManage/save',
        payload: {
          menuList: newData,
        },
      });
    }
  };
  remove(record) {
    const { menuList, dispatch } = this.props;
    const newData = depCopy(menuList);
    const restData = deleteItemByKey(record.key, newData);
    confirm({
      title: '确认是否删除?',
      onOk() {
        if (record.id) {
          dispatch({
            type: 'menuManage/deleteMenu',
            payload: { id: record.id },
          });
        }
        dispatch({
          type: 'menuManage/save',
          payload: {
            menuList: restData,
          },
        });
      },
    });
  }
  newMember = () => {
    const { menuList, dispatch } = this.props;
    const newData = depCopy(menuList);
    const X = moment().format('X');
    newData.push({
      key: X,
      id: '',
      path: '',
      name: '',
      icon: '',
      priority: '',
      editable: true,
      isNew: true,
    });
    dispatch({
      type: 'menuManage/save',
      payload: {
        menuList: newData,
      },
    });
  };
  handleKeyPress(e, key) {
    if (e.key === 'Enter') {
      this.saveRow(e, key);
    }
  }
  handleFieldChange(e, fieldName, key) {
    const { menuList, dispatch } = this.props;
    const newData = depCopy(menuList);
    const target = findItemByKey(key, newData);
    if (target) {
      target[fieldName] = e.target.value;
      dispatch({
        type: 'menuManage/save',
        payload: {
          menuList: newData,
        },
      });
    }
  }
  handleSelectFieldChange(e, fieldName, key) {
    if (e.includes('0')) {
      e = ['0'];
    }

    const { menuList, dispatch } = this.props;
    const newData = depCopy(menuList);
    const target = findItemByKey(key, newData);

    if (target) {
      target[fieldName] = e;
      target['roleIds'] = [];
      for (let item of e) {
        target['roleIds'].push({
          roleId: item,
          resId: target.id,
        });
      }

      dispatch({
        type: 'menuManage/save',
        payload: {
          menuList: newData,
        },
      });
    }
  }
  handleTreeFieldChange(value, label, fieldName, key) {
    const { menuList, dispatch } = this.props;
    const newData = depCopy(menuList);
    const target = findItemByKey(key, newData);
    if (target) {
      target[fieldName] = value;
      dispatch({
        type: 'menuManage/save',
        payload: {
          menuList: newData,
        },
      });
    }
  }
  saveRow(e, key) {
    e.persist();

    const { dispatch, menuList } = this.props;

    if (this.clickedCancel) {
      this.clickedCancel = false;
      return;
    }

    const target = findItemByKey(key, menuList);
    if (!target.name || !target.path) {
      message.error('请填写完整成员信息。');
      e.target.focus();
      return;
    }

    if (!target.id) {
      const newId = (getLastId(target.pid, menuList) + 1).toString();
      target.id = newId;
      target.priority = newId;
      dispatch({
        type: 'menuManage/addMenu',
        payload: { ...target },
      });
    } else {
      dispatch({
        type: 'menuManage/updateMenu',
        payload: target,
      });
    }
  }
  cancel(e, key) {
    this.clickedCancel = true;
    e.preventDefault();

    const { dispatch, menuList } = this.props;

    const newData = depCopy(menuList);
    const target = findItemByKey(key, newData);
    if (this.cacheOriginData[key]) {
      Object.assign(target, this.cacheOriginData[key]);
      target.editable = false;
      delete this.cacheOriginData[key];
    }
    dispatch({
      type: 'menuManage/save',
      payload: {
        menuList: newData,
      },
    });
    this.clickedCancel = false;
  }

  render() {
    const { loading, menuList, rolesList } = this.props;

    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 150,
      },
      {
        title: '父菜单',
        dataIndex: 'pid',
        key: 'pid',
        render: (text, record) => {
          if (record.editable && !record.id) {
            return (
              <TreeSelect
                style={{ width: 150 }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={menuList}
                placeholder='父菜单'
                treeDefaultExpandAll
                onChange={(value, label) => this.handleTreeFieldChange(value, label, 'pid', record.key)}
                value={text}
              />
            );
          }
          return <div className={styles.textCenter}>{findNameById(text, menuList)}</div>;
        },
      },
      {
        title: '菜单名称',
        dataIndex: 'name',
        key: 'name',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'name', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='菜单名称'
              />
            );
          }
          return <div className={styles.textCenter}>{text}</div>;
        },
      },
      {
        title: '地址',
        dataIndex: 'path',
        key: 'path',
        render: (text, record) => {
          if (record.editable) {
            return <Input value={text} onChange={(e) => this.handleFieldChange(e, 'path', record.key)} onKeyPress={(e) => this.handleKeyPress(e, record.key)} placeholder='地址' />;
          }
          return <div className={styles.textCenter}>{text}</div>;
        },
      },
      {
        title: '图标',
        dataIndex: 'icon',
        key: 'icon',
        render: (text, record) => {
          if (record.editable) {
            return <Input value={text} onChange={(e) => this.handleFieldChange(e, 'icon', record.key)} onKeyPress={(e) => this.handleKeyPress(e, record.key)} placeholder='图标' />;
          }
          return <div className={styles.textCenter}>{text}</div>;
        },
      },
      /*{
        title: '优先级',
        dataIndex: 'priority',
        key: 'priority',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                type='number'
                value={text}
                onChange={e => this.handleFieldChange(e, 'priority', record.key)}
                onKeyPress={e => this.handleKeyPress(e, record.key)}
                placeholder="优先级"
              />
            );
          }
          return text;
        },
      },*/
      {
        title: '权限列表',
        dataIndex: 'roleIdsArr',
        key: 'roleIdsArr',
        width: 150,
        render: (text, record) => {
          if (record.editable) {
            return (
              <Select
                mode='multiple'
                style={{ width: '100%' }}
                placeholder='请选择工号'
                defaultValue={text}
                onChange={(e) => this.handleSelectFieldChange(e, 'roleIdsArr', record.key)}
              >
                {rolesList.map((d) => (
                  <Option value={d.key}>{d.key + '-' + d.value}</Option>
                ))}
              </Select>
            );
          } else {
            const rs = [];
            for (let code of text) {
              const name = rolesList.find((item) => {
                return item.key === code;
              });
              if (name) {
                rs.push(name);
              }
            }
            let str = '';
            for (let item of rs) {
              str += item.key + '-' + item.value + ',';
            }
            return (
              <div className={styles.ellipsis} style={{ width: 100 }}>
                {str.substring(0, str.length - 1)}
              </div>
            );
          }
        },
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => {
          if (!!record.editable && loading) {
            return null;
          }
          if (record.editable) {
            if (record.isNew) {
              return (
                <div className={styles.textCenter}>
                  <span>
                    <a onClick={(e) => this.saveRow(e, record.key)}>添加</a>
                    <Divider type='vertical' />
                    {/* <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record)}> */}
                    <a onClick={() => this.remove(record)}>删除</a>
                    {/* </Popconfirm> */}
                  </span>
                </div>
              );
            }
            return (
              <div className={styles.textCenter}>
                <span>
                  <a onClick={(e) => this.saveRow(e, record.key)}>保存</a>
                  <Divider type='vertical' />
                  <a onClick={(e) => this.cancel(e, record.key)}>取消</a>
                </span>
              </div>
            );
          }
          return (
            <div className={styles.textCenter}>
              <span>
                <a onClick={(e) => this.toggleEditable(e, record.key)}>编辑</a>
                <Divider type='vertical' />
                {/* <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record)}> */}
                <a onClick={() => this.remove(record)}>删除</a>
                {/* </Popconfirm> */}
              </span>
            </div>
          );
        },
      },
    ];
    return (
      <Fragment>
        <Table
          className={styles.TdTextLeft}
          loading={loading}
          columns={columns}
          dataSource={menuList}
          pagination={false}
          rowClassName={(record) => {
            return record.editable ? styles.editable : '';
          }}
        />
        <Button style={{ width: '100%', marginTop: 16, marginBottom: 8 }} type='dashed' onClick={this.newMember} icon={<PlusOutlined />}>
          新增菜单
        </Button>
      </Fragment>
    );
  }
}
